package com.lab.tools;

import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import com.lab.logtrack.AppLog;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 用于管理悬浮窗的Service
 * <p/>
 * modify by ak
 * 增加桌面歌词的控制逻辑
 */
public class FloatWindowService extends Service {

    /**
     * 定时器，定时进行检测当前应该创建还是移除悬浮窗。
     */
    private Timer timer;

    private boolean isFloatWindowOpen = true; //是否显示悬浮窗
    private boolean isFloatWindowTop; //是否置顶显示


    /**
     * 用于在线程中创建或移除悬浮窗。
     */
    private Handler mHandler = new Handler();

    /**
     * 监听来电
     */
    private PhoneStateListener mPhoneListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            // 来电时关闭大悬浮窗
            if (state != TelephonyManager.CALL_STATE_IDLE) {
                FloatWindowManager.removeFloatMainWindow(getApplicationContext());
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    };

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                FloatWindowManager.removeFloatMainWindow(getApplicationContext());
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        AppLog.d("FloatWindowService onCreate");
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isFloatWindowOpen) {
                    FloatWindowManager.showFloatSmallWindowView(getApplication());
                }
            }
        }, 500);


        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 开启定时器，每隔1秒刷新一次
        if (timer == null) {
            timer = new Timer();
            timer.scheduleAtFixedRate(new RefreshTask(), 0, 1000);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {

        FloatWindowManager.removeSmallWindow(getApplicationContext());
        FloatWindowManager.removeFloatMainWindow(getApplicationContext());

        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        tm.listen(mPhoneListener, PhoneStateListener.LISTEN_NONE);

        unregisterReceiver(mReceiver);
        // Service被终止的同时也停止定时器继续运行
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.onDestroy();

    }

    class RefreshTask extends TimerTask {

        @Override
        public void run() {
            boolean isHome = isHome();
            boolean isOurApp = isOurApp();
            // 当前界面是app，且没有悬浮窗显示，则创建悬浮窗。
            if (isOurApp && !FloatWindowManager.isWindowShowing()) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (isFloatWindowOpen) {
                            FloatWindowManager.showFloatSmallWindowView(getApplicationContext());
                        }
                    }
                });
            }

            if (!isOurApp && FloatWindowManager.isWindowShowing()) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        FloatWindowManager.removeSmallWindow(getApplicationContext());
                    }
                });
            }
        }

    }

    /**
     * 判断当前界面是否是桌面
     */
    private boolean isHome() {
        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
        try {
            return getHomes().contains(rti.get(0).topActivity.getPackageName());
        } catch (Exception e) {
            AppLog.w(e.getMessage());
        }
        return true;
    }

    /**
     * 判断当前界面是否是app打开
     */
    private boolean isOurApp() {
        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
        if (rti == null || rti.size() == 0 || getApplicationContext() == null) {
            return false;
        }
        ComponentName activity = rti.get(0).topActivity;
        if (activity == null) {
            return false;
        }
        return activity.getPackageName().equals(getApplicationContext().getPackageName());
    }

    /**
     * 获得属于桌面的应用的应用包名称
     *
     * @return 返回包含所有包名的字符串列表
     */
    private List<String> getHomes() {
        List<String> names = new ArrayList<String>();
        PackageManager packageManager = this.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        try {
            List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo ri : resolveInfo) {
                names.add(ri.activityInfo.packageName);
            }
        } catch (Exception e) {
            AppLog.w(e.getMessage());
        }
        return names;
    }
}
